package com.xuecheng.order.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.service.WxPayService;
import com.xuecheng.api.order.OrdersApi;
import com.xuecheng.api.order.model.dto.OrdersDTO;
import com.xuecheng.common.domain.uaa.LoginUser;
import com.xuecheng.order.common.utils.UAASecurityUtil;
import com.xuecheng.order.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author itcast
 */
@Slf4j
@RestController
public class OrdersController implements OrdersApi {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private WxPayService wxPayService;

    @GetMapping("orders/create/{coursePubId}")
    public OrdersDTO createOrder(@PathVariable Long coursePubId) {

        LoginUser user = UAASecurityUtil.getUser();
        String username = user.getUsername();
        return ordersService.createOrder(coursePubId, username);
    }

    @GetMapping("orderPay/wxPay/createPay")
    public Map<String, Object> createOrderPay(String orderNo) {
        LoginUser user = UAASecurityUtil.getUser();
        String username = user.getUsername();
        return ordersService.createOrderPay(orderNo, username);
    }


    /**
     * 支付完毕，前端回调，查询课程支付状态， 跳转课程详情页
     * @param orderNo
     * @return
     */
    @GetMapping("orders/{orderNo}")
    public OrdersDTO getOrderByOrderNo(@PathVariable String orderNo) {

        return ordersService.getOrderByOrderNo(orderNo);
    }

    /**
     * <p>
     * 支付平台发送消息通知交易操作的结果
     * </p>
     *
     * @param request  http请求
     * @param response http响应
     * @return String
     */
    @RequestMapping("order-pay/wx-pay/notify-result")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {

        try {
            log.info("收到支付平台发送的消息通知交易结果");
            String resultStr = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());

            return ordersService.payNotify(resultStr);
        } catch (IOException e) {
            log.error("通知消息解析失败,{}", e.getMessage());
            return WxPayNotifyResponse.fail("支付消息通知失败");
        }
    }

}
